package com.wwz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.wwz.pojo.Room;
import com.wwz.pojo.RoomQuery;
import com.wwz.repository.RoomRepository;
import com.wwz.service.RoomService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoomServiceImpl implements RoomService {

    @Resource
    private RoomRepository repository;


    @Override
    public Room add(Room room) {
        return repository.save(room);
    }

    @Override
    public void delete(Integer id) {
        repository.deleteById(id);
    }

    @Override
    public Room upData(Integer id,Room room) {
        Room one = repository.getOne(id);
        BeanUtil.copyProperties(room,one);
        return repository.save(one);
    }

    @Override
    public List<Room> findAll() {
        return repository.findAll();
    }

    @Override
    public Room getOne(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public Page<Room> toPage(Integer page, Integer size) {
        Sort sort = Sort.by(Sort.Order.asc("roomId"));
        Pageable pageable = PageRequest.of(page, size, sort);
        return repository.findAll(pageable);
    }

    @Override
    public Page<Room> toPage2(Integer page, Integer size, RoomQuery query) {
        Sort sort = Sort.by(Sort.Order.asc("roomId"));
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<Room> rooms = repository.findAll((Specification<Room>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            // 精确匹配
            if (StrUtil.isNotEmpty(query.getRoomName())){
                list.add(criteriaBuilder.equal(root.get("roomName"), query.getRoomName()));
            }
            // 模糊匹配
            if (StrUtil.isNotEmpty(query.getRoomType())){
                list.add(criteriaBuilder.like(root.get("roomType"),"%"+query.getRoomType()+"%"));
            }
            // gt大于  ge->大于等于 ， lt小于   le->小于等于
            if (query.getRoomNum()!=null && query.getRoomNum()>0){
                //list.add(criteriaBuilder.gt(root.get("roomNum"),query.getRoomNum()));
                list.add(criteriaBuilder.between(root.get("roomNum"),3,5));
            }
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        }, pageable);
        return rooms;
    }
}
